package com.woniuxy.factory.service.imp;

import com.woniuxy.factory.entity.Equipment;
import com.woniuxy.factory.entity.RepairApply;
import com.woniuxy.factory.mapper.EquipmentMapper;
import com.woniuxy.factory.mapper.RepairApplyMapper;
import com.woniuxy.factory.service.ApplyService;
import com.woniuxy.factory.util.UuidUtil;
import lombok.Data;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ApplyServiceImp implements ApplyService {
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    RepairApplyMapper repairApplyMapper;

    @Override
    @Transactional
    public void repairApply(int eid, String reason) throws Exception {
        //查找是否有该设备，并且该设备状态
        String state = equipmentMapper.selectEquimentById(eid);
        if (state == null) {
            throw new RuntimeException("没有该设备");
        } else if (!state.equals("正常")) {
            throw new RuntimeException("该设备已为异常，请勿重复申请");
        }
        try {
            //通过eid找到指定设备，并将其状态置为异常
            Equipment equipment = new Equipment();
            equipment.setEid(eid);
            equipment.setState("异常");
            equipmentMapper.updateEquipment(equipment);
            //将申请表单中的信息插入到数据库中
            RepairApply repairApply = new RepairApply();
            repairApply.setRepId(UuidUtil.get16UUID());
            repairApply.setEid(eid);
            repairApply.setReason(reason);
            repairApply.setState("未受理");
            repairApply.setCreatTime(new Date());
            repairApplyMapper.insertRepairApply(repairApply);
        } catch (Exception e) {
            throw new Exception("申请失败，请重新申请");
        }
    }

    @Override
    public List<RepairApply> showEquipmentApply(RepairApply repairApply, String searchTime) {
        //非空验证
        String begin = null;
        String end = null;
        if (searchTime!= null && searchTime!="") {
            begin = searchTime.substring(0, 10);
            end = searchTime.substring(13, 23);
        }
        return repairApplyMapper.selectRepairApply(repairApply, begin, end);
    }
}